import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  Tag,
  Tooltip,
  Row,
  Col,
  Typography,
  Tree,
  InputNumber,
  message,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  ReloadOutlined,
  SettingOutlined,
  MenuOutlined,
  ApiOutlined,
  BranchesOutlined,
  DashboardOutlined,
  TableOutlined,
  UserOutlined,
  TeamOutlined,
  AppstoreOutlined,
  SafetyOutlined,
  HomeOutlined,
  FileTextOutlined,
  BarChartOutlined,
  DatabaseOutlined,
  CloudOutlined,
  ToolOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { TreeDataNode } from 'antd/es/tree';
import { useAuth } from '../contexts/AuthContext';
import { useTheme } from '../contexts/ThemeContext';
import { showNotification } from '../utils/notification';
import { requestGuard } from '../utils/requestGuard';
import api from '../services/api';
import DragSortTree from '../components/DragSortTree';
import RouteStatistics from '../components/RouteStatistics';



const { Title, Text } = Typography;
const { TextArea } = Input;

// 图标映射
const iconMap: Record<string, any> = {
  DashboardOutlined,
  TableOutlined,
  UserOutlined,
  TeamOutlined,
  AppstoreOutlined,
  SafetyOutlined,
  HomeOutlined,
  FileTextOutlined,
  BarChartOutlined,
  DatabaseOutlined,
  CloudOutlined,
  ToolOutlined,
  SettingOutlined,
  BranchesOutlined,
  MenuOutlined,
  ApiOutlined,
};

// 图标选项
const iconOptions = Object.keys(iconMap).map(key => ({
  label: key,
  value: key,
  icon: React.createElement(iconMap[key]),
}));

// 路由数据接口
interface Route {
  id: number;
  path: string;
  name: string;
  display_name: string;
  description?: string;
  icon?: string;
  component?: string;
  parent_id?: number;
  sort_order: number;
  is_menu: boolean;
  is_active: boolean;
  is_system: boolean;
  meta?: Record<string, any>;
  created_at: string;
  updated_at: string;
  children?: Route[];
  permissions?: Permission[];
  permission_names?: string[];
}

interface Permission {
  id: number;
  name: string;
  display_name: string;
  description?: string;
}

const RouteManagement: React.FC = () => {
  const { currentTheme } = useTheme();
  
  // 状态管理
  const [routes, setRoutes] = useState<Route[]>([]);
  const [permissions, setPermissions] = useState<Permission[]>([]);
  const [loading, setLoading] = useState(false);

  const [showStatistics, setShowStatistics] = useState(false);
  
  // 模态框状态
  const [isCreateModalVisible, setIsCreateModalVisible] = useState(false);
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [isPermissionModalVisible, setIsPermissionModalVisible] = useState(false);
  const [isSortModalVisible, setIsSortModalVisible] = useState(false);

  const [currentRoute, setCurrentRoute] = useState<Route | null>(null);
  const [selectedPermissions, setSelectedPermissions] = useState<number[]>([]);
  
  // 表单实例
  const [createForm] = Form.useForm();
  const [editForm] = Form.useForm();
  
  // 防重复请求
  const routesLoadedRef = useRef(false);
  const permissionsLoadedRef = useRef(false);
  
  // 权限检查
  const { hasPermission } = useAuth();
  const routePermissions = useMemo(() => ({
    canViewRoutes: hasPermission('route.view'),
    canCreateRoutes: hasPermission('route.create'),
    canUpdateRoutes: hasPermission('route.update'),
    canDeleteRoutes: hasPermission('route.delete'),
    canManagePermissions: hasPermission('route.manage'),
  }), [hasPermission]);

  /**
   * 获取路由列表
   */
  const fetchRoutes = useCallback(async () => {
    if (!routePermissions.canViewRoutes) return;
    
    if (!requestGuard.canRequest('fetchRoutes')) {
      return;
    }

    try {
      setLoading(true);
      

      const response = await api.get('/v1/routes/tree');
      setRoutes(response.data.data);
      routesLoadedRef.current = true;
    } catch (error: any) {
      console.error('获取路由列表失败:', error);
      showNotification('error', '获取路由列表失败', error.message);
    } finally {
      setLoading(false);
      requestGuard.completeRequest('fetchRoutes');
    }
  }, [routePermissions.canViewRoutes]);

  /**
   * 获取权限列表
   */
  const fetchPermissions = useCallback(async () => {
    if (permissionsLoadedRef.current) {
      return;
    }

    if (!requestGuard.canRequest('fetchPermissions-for-route')) {
      return;
    }

    try {
      const response = await api.get('/v1/permissions');
      setPermissions(response.data.data.permissions);
      permissionsLoadedRef.current = true;
    } catch (error: any) {
      showNotification('error', '获取权限列表失败', error.message);
    } finally {
      requestGuard.completeRequest('fetchPermissions-for-route');
    }
  }, []);

  // 初始化数据获取
  useEffect(() => {
    if (!routePermissions.canViewRoutes) return;



    // 清除可能存在的请求防护状态（页面刷新时）
    requestGuard.clearGuard('fetchRoutes');
    requestGuard.clearGuard('fetchPermissions-for-route');

    // 获取权限数据（只获取一次）
    if (!permissionsLoadedRef.current) {
      fetchPermissions();
    }

    // 获取路由数据
    fetchRoutes();
  }, [routePermissions.canViewRoutes]); // 移除函数依赖，避免无限循环





  /**
   * 创建路由
   */
  const handleCreate = async (values: any) => {
    try {
      await api.post('/v1/routes', values);
      showNotification('success', '路由创建成功');
      setIsCreateModalVisible(false);
      createForm.resetFields();
      routesLoadedRef.current = false;
      fetchRoutes();
    } catch (error: any) {
      showNotification('error', '路由创建失败', error.message);
    }
  };

  /**
   * 更新路由
   */
  const handleUpdate = async (values: any) => {
    if (!currentRoute) return;
    
    try {
      await api.put(`/v1/routes/${currentRoute.id}`, values);
      showNotification('success', '路由更新成功');
      setIsEditModalVisible(false);
      editForm.resetFields();
      setCurrentRoute(null);
      routesLoadedRef.current = false;
      fetchRoutes();
    } catch (error: any) {
      showNotification('error', '路由更新失败', error.message);
    }
  };

  /**
   * 删除路由
   */
  const handleDelete = (route: Route) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除路由 "${route.display_name}" 吗？此操作不可恢复。`,
      okText: '确定',
      cancelText: '取消',
      okType: 'danger',
      centered: true,
      onOk: async () => {
        try {
          await api.delete(`/v1/routes/${route.id}`);
          showNotification('success', '路由删除成功');
          routesLoadedRef.current = false;
          fetchRoutes();
        } catch (error: any) {
          showNotification('error', '路由删除失败', error.message);
        }
      },
    });
  };

  /**
   * 打开编辑模态框
   */
  const openEditModal = (route: Route) => {
    setCurrentRoute(route);
    editForm.setFieldsValue({
      name: route.name,
      display_name: route.display_name,
      description: route.description,
      icon: route.icon,
      component: route.component,
      parent_id: route.parent_id,
      sort_order: route.sort_order,
      is_menu: route.is_menu,
      is_active: route.is_active,
      meta: route.meta ? JSON.stringify(route.meta, null, 2) : undefined,
    });
    setIsEditModalVisible(true);
  };

  /**
   * 打开详情模态框
   */
  const openDetailModal = (route: Route) => {
    setCurrentRoute(route);
    setIsDetailModalVisible(true);
  };

  /**
   * 打开权限分配模态框
   */
  const openPermissionModal = (route: Route) => {
    setCurrentRoute(route);
    setSelectedPermissions(route.permissions?.map(p => p.id) || []);
    setIsPermissionModalVisible(true);
  };

  /**
   * 保存权限分配
   */
  const handleSavePermissions = async () => {
    if (!currentRoute) return;

    try {
      await api.post(`/v1/routes/${currentRoute.id}/permissions`, {
        permission_ids: selectedPermissions,
      });
      showNotification('success', '权限分配成功');
      setIsPermissionModalVisible(false);
      setCurrentRoute(null);
      setSelectedPermissions([]);
      routesLoadedRef.current = false;
      fetchRoutes();
    } catch (error: any) {
      showNotification('error', '权限分配失败', error.message);
    }
  };

  /**
   * 批量更新路由排序
   */
  const handleBatchSort = async (sortData: any[]) => {
    try {
      await api.put('/v1/routes/batch-sort', sortData);
      showNotification('success', '路由排序更新成功');
      routesLoadedRef.current = false;
      fetchRoutes();
    } catch (error: any) {
      showNotification('error', '路由排序更新失败', error.message);
      throw error;
    }
  };



  /**
   * 转换路由数据为拖拽排序格式
   */
  const convertRoutesToSortData = (routes: Route[]): any[] => {
    if (!routes || !Array.isArray(routes)) return [];

    return routes.map(route => {
      // 创建干净的数据对象，避免循环引用
      const converted = {
        id: route.id,
        key: route.id.toString(),
        title: route.display_name || route.name || '未命名路由',
        display_name: route.display_name,
        name: route.name,
        path: route.path,
        sort_order: route.sort_order,
        parent_id: route.parent_id,
        is_menu: route.is_menu,
        is_active: route.is_active,
        is_system: route.is_system,
        icon: route.icon,
        component: route.component,
        description: route.description
      };

      // 递归处理子路由，避免循环引用
      if (route.children && Array.isArray(route.children) && route.children.length > 0) {
        converted.children = convertRoutesToSortData(route.children);
      }

      return converted;
    });
  };

  /**
   * 获取路由状态标签
   */
  const getRouteStatusTag = (route: Route) => {
    const tags = [];
    
    if (route.is_system) {
      tags.push(<Tag key="system" color="blue">系统路由</Tag>);
    } else {
      tags.push(<Tag key="custom" color="green">自定义路由</Tag>);
    }
    
    if (route.is_menu) {
      tags.push(<Tag key="menu" color="purple">菜单项</Tag>);
    }
    
    if (!route.is_active) {
      tags.push(<Tag key="inactive" color="red">已禁用</Tag>);
    }
    
    return <Space>{tags}</Space>;
  };

  /**
   * 构建父路由选项
   */
  const buildParentOptions = (routes: Route[], level = 0): any[] => {
    const options: any[] = [];
    
    routes.forEach(route => {
      options.push({
        label: `${'  '.repeat(level)}${route.display_name}`,
        value: route.id,
      });
      
      if (route.children && route.children.length > 0) {
        options.push(...buildParentOptions(route.children, level + 1));
      }
    });
    
    return options;
  };

  // 表格列定义
  const columns: ColumnsType<Route> = [
    {
      title: '路由信息',
      key: 'info',
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold', marginBottom: 4 }}>
            {record.icon && iconMap[record.icon] && (
              <span style={{ marginRight: 8 }}>
                {React.createElement(iconMap[record.icon])}
              </span>
            )}
            {record.display_name}
          </div>
          <div style={{ fontSize: '12px', color: currentTheme.colorTextSecondary }}>
            {record.path}
          </div>
          <div style={{ fontSize: '12px', color: currentTheme.colorTextTertiary }}>
            {record.name}
          </div>
        </div>
      ),
    },
    {
      title: '状态',
      key: 'status',
      width: 160,
      render: (_, record) => getRouteStatusTag(record),
    },
    {
      title: '排序',
      dataIndex: 'sort_order',
      key: 'sort_order',
      width: 70,
      align: 'center',
    },
    {
      title: '权限',
      key: 'permissions',
      width: 120,
      render: (_, record) => (
        <div>
          {record.permission_names && record.permission_names.length > 0 ? (
            <Space wrap>
              {record.permission_names.slice(0, 2).map(name => (
                <Tag key={name} size="small">{name}</Tag>
              ))}
              {record.permission_names.length > 2 && (
                <Tag size="small">+{record.permission_names.length - 2}</Tag>
              )}
            </Space>
          ) : (
            <Text type="secondary">无权限要求</Text>
          )}
        </div>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 160,
      fixed: 'right' as const,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => openDetailModal(record)}
            />
          </Tooltip>
          {routePermissions.canUpdateRoutes && !record.is_system && (
            <Tooltip title="编辑">
              <Button
                type="text"
                size="small"
                icon={<EditOutlined />}
                onClick={() => openEditModal(record)}
              />
            </Tooltip>
          )}
          {routePermissions.canManagePermissions && (
            <Tooltip title="权限配置">
              <Button
                type="text"
                size="small"
                icon={<SettingOutlined />}
                onClick={() => openPermissionModal(record)}
              />
            </Tooltip>
          )}
          {routePermissions.canDeleteRoutes && !record.is_system && (
            <Tooltip title="删除">
              <Button
                type="text"
                size="small"
                danger
                icon={<DeleteOutlined />}
                onClick={() => handleDelete(record)}
              />
            </Tooltip>
          )}
        </Space>
      ),
    },
  ];

  if (!routePermissions.canViewRoutes) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Text type="secondary">您没有权限查看路由管理页面</Text>
      </div>
    );
  }

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <div style={{ marginBottom: '16px' }}>
          <Row justify="space-between" align="middle" gutter={[16, 16]}>
            <Col xs={24} sm={24} md={12} lg={8} xl={8}>
              <Title level={4} style={{ margin: 0 }}>
                <BranchesOutlined style={{ marginRight: 8 }} />
                路由管理
              </Title>
            </Col>
            <Col xs={24} sm={24} md={12} lg={16} xl={16}>
              <div style={{ display: 'flex', justifyContent: 'flex-end', flexWrap: 'wrap', gap: '8px' }}>
                {routePermissions.canCreateRoutes && (
                  <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={() => setIsCreateModalVisible(true)}
                  >
                    新建路由
                  </Button>
                )}
                {routePermissions.canManagePermissions && (
                  <Button
                    icon={<MenuOutlined />}
                    onClick={() => setIsSortModalVisible(true)}
                  >
                    拖拽排序
                  </Button>
                )}
                <Button
                  icon={<BarChartOutlined />}
                  onClick={() => setShowStatistics(!showStatistics)}
                  type={showStatistics ? 'primary' : 'default'}
                >
                  {showStatistics ? '隐藏统计' : '显示统计'}
                </Button>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={() => {
                    routesLoadedRef.current = false;
                    fetchRoutes();
                  }}
                >
                  刷新
                </Button>
              </div>
            </Col>
          </Row>
        </div>



        {/* 路由统计 */}
        {showStatistics && (
          <div style={{ marginBottom: 16 }}>
            <RouteStatistics />
          </div>
        )}

        {/* 路由表格 */}
        <Table
          columns={columns}
          dataSource={routes}
          rowKey="id"
          loading={loading}
          pagination={false}
          expandable={{
            childrenColumnName: 'children',
            defaultExpandAllRows: true,
          }}
          scroll={{ x: 'max-content' }}
        />
      </Card>

      {/* 创建路由模态框 */}
      <Modal
        title={
          <Space>
            <PlusOutlined />
            新建路由
          </Space>
        }
        open={isCreateModalVisible}
        onCancel={() => {
          setIsCreateModalVisible(false);
          createForm.resetFields();
        }}
        width="90%"
        style={{ maxWidth: '800px' }}
        footer={
          <div style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setIsCreateModalVisible(false);
                createForm.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" onClick={() => createForm.submit()}>
                创建
              </Button>
            </Space>
          </div>
        }
        destroyOnClose
      >
        <Form
          form={createForm}
          layout="vertical"
          onFinish={handleCreate}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="path"
                label="路由路径"
                rules={[
                  { required: true, message: '请输入路由路径' },
                  { pattern: /^\//, message: '路由路径必须以 / 开头' },
                ]}
              >
                <Input placeholder="如: /dashboard" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="name"
                label="路由名称"
                rules={[{ required: true, message: '请输入路由名称' }]}
              >
                <Input placeholder="如: dashboard" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="display_name"
                label="显示名称"
                rules={[{ required: true, message: '请输入显示名称' }]}
              >
                <Input placeholder="如: 仪表盘" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="icon"
                label="图标"
              >
                <Select
                  placeholder="选择图标"
                  allowClear
                  showSearch
                  optionFilterProp="label"
                >
                  {iconOptions.map(option => (
                    <Select.Option key={option.value} value={option.value} label={option.label}>
                      <Space>
                        {option.icon}
                        {option.label}
                      </Space>
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="描述"
          >
            <TextArea rows={2} placeholder="路由描述..." />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="component"
                label="组件路径"
              >
                <Input placeholder="如: pages/Dashboard" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="parent_id"
                label="父路由"
              >
                <Select placeholder="选择父路由" allowClear>
                  {buildParentOptions(routes).map(option => (
                    <Select.Option key={option.value} value={option.value}>
                      {option.label}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={[16, 16]}>
            <Col xs={24} sm={12} md={8}>
              <Form.Item
                name="sort_order"
                label="排序"
                initialValue={0}
              >
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={8}>
              <Form.Item
                name="is_menu"
                label="菜单项"
                valuePropName="checked"
                initialValue={true}
              >
                <div style={{ display: 'flex', alignItems: 'center', height: '32px' }}>
                  <Switch checkedChildren="是" unCheckedChildren="否" />
                </div>
              </Form.Item>
            </Col>
            <Col xs={24} sm={12} md={8}>
              <Form.Item
                name="is_active"
                label="启用状态"
                valuePropName="checked"
                initialValue={true}
              >
                <div style={{ display: 'flex', alignItems: 'center', height: '32px' }}>
                  <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                </div>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="meta"
            label="元数据 (JSON)"
          >
            <TextArea
              rows={3}
              placeholder='{"key": "value"}'
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑路由模态框 */}
      <Modal
        title={
          <Space>
            <EditOutlined />
            编辑路由
          </Space>
        }
        open={isEditModalVisible}
        onCancel={() => {
          setIsEditModalVisible(false);
          editForm.resetFields();
          setCurrentRoute(null);
        }}
        width="90%"
        style={{ maxWidth: '800px' }}
        footer={
          <div style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setIsEditModalVisible(false);
                editForm.resetFields();
                setCurrentRoute(null);
              }}>
                取消
              </Button>
              <Button type="primary" onClick={() => editForm.submit()}>
                保存
              </Button>
            </Space>
          </div>
        }
        destroyOnClose
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={handleUpdate}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="路由名称"
                rules={[{ required: true, message: '请输入路由名称' }]}
              >
                <Input placeholder="如: dashboard" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="display_name"
                label="显示名称"
                rules={[{ required: true, message: '请输入显示名称' }]}
              >
                <Input placeholder="如: 仪表盘" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="描述"
          >
            <TextArea rows={2} placeholder="路由描述..." />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="icon"
                label="图标"
              >
                <Select
                  placeholder="选择图标"
                  allowClear
                  showSearch
                  optionFilterProp="label"
                >
                  {iconOptions.map(option => (
                    <Select.Option key={option.value} value={option.value} label={option.label}>
                      <Space>
                        {option.icon}
                        {option.label}
                      </Space>
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="component"
                label="组件路径"
              >
                <Input placeholder="如: pages/Dashboard" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="parent_id"
                label="父路由"
              >
                <Select placeholder="选择父路由" allowClear>
                  {buildParentOptions(routes).filter(option => option.value !== currentRoute?.id).map(option => (
                    <Select.Option key={option.value} value={option.value}>
                      {option.label}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="sort_order"
                label="排序"
              >
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={[16, 16]}>
            <Col xs={24} sm={12}>
              <Form.Item
                name="is_menu"
                label="菜单项"
                valuePropName="checked"
              >
                <div style={{ display: 'flex', alignItems: 'center', height: '32px' }}>
                  <Switch checkedChildren="是" unCheckedChildren="否" />
                </div>
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item
                name="is_active"
                label="启用状态"
                valuePropName="checked"
              >
                <div style={{ display: 'flex', alignItems: 'center', height: '32px' }}>
                  <Switch checkedChildren="启用" unCheckedChildren="禁用" />
                </div>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="meta"
            label="元数据 (JSON)"
          >
            <TextArea
              rows={3}
              placeholder='{"key": "value"}'
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 路由详情模态框 */}
      <Modal
        title={
          <Space>
            <EyeOutlined />
            路由详情
          </Space>
        }
        open={isDetailModalVisible}
        onCancel={() => {
          setIsDetailModalVisible(false);
          setCurrentRoute(null);
        }}
        width="90%"
        style={{ maxWidth: '800px' }}
        footer={
          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => {
              setIsDetailModalVisible(false);
              setCurrentRoute(null);
            }}>
              关闭
            </Button>
          </div>
        }
        destroyOnClose
      >
        {currentRoute && (
          <div>
            <Row gutter={16}>
              <Col span={12}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>路由路径：</Text>
                  <div style={{ marginTop: 4 }}>
                    <Tag color="blue">{currentRoute.path}</Tag>
                  </div>
                </div>
              </Col>
              <Col span={12}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>路由名称：</Text>
                  <div style={{ marginTop: 4 }}>{currentRoute.name}</div>
                </div>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>显示名称：</Text>
                  <div style={{ marginTop: 4 }}>{currentRoute.display_name}</div>
                </div>
              </Col>
              <Col span={12}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>图标：</Text>
                  <div style={{ marginTop: 4 }}>
                    {currentRoute.icon ? (
                      <Tag>{currentRoute.icon}</Tag>
                    ) : (
                      <Text type="secondary">无</Text>
                    )}
                  </div>
                </div>
              </Col>
            </Row>

            {currentRoute.description && (
              <div style={{ marginBottom: 16 }}>
                <Text strong>描述：</Text>
                <div style={{ marginTop: 4 }}>{currentRoute.description}</div>
              </div>
            )}

            <Row gutter={16}>
              <Col span={12}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>组件路径：</Text>
                  <div style={{ marginTop: 4 }}>
                    {currentRoute.component ? (
                      <Tag color="green">{currentRoute.component}</Tag>
                    ) : (
                      <Text type="secondary">无</Text>
                    )}
                  </div>
                </div>
              </Col>
              <Col span={12}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>排序：</Text>
                  <div style={{ marginTop: 4 }}>{currentRoute.sort_order}</div>
                </div>
              </Col>
            </Row>

            <div style={{ marginBottom: 16 }}>
              <Text strong>状态：</Text>
              <div style={{ marginTop: 4 }}>
                {getRouteStatusTag(currentRoute)}
              </div>
            </div>

            {currentRoute.permissions && currentRoute.permissions.length > 0 && (
              <div style={{ marginBottom: 16 }}>
                <Text strong>所需权限：</Text>
                <div style={{ marginTop: 4 }}>
                  <Space wrap>
                    {currentRoute.permissions.map(permission => (
                      <Tag key={permission.id} color="orange">
                        {permission.display_name}
                      </Tag>
                    ))}
                  </Space>
                </div>
              </div>
            )}

            {currentRoute.meta && (
              <div style={{ marginBottom: 16 }}>
                <Text strong>元数据：</Text>
                <div style={{ marginTop: 4 }}>
                  <pre style={{
                    background: currentTheme.colorBgContainer,
                    padding: 12,
                    borderRadius: 6,
                    fontSize: '12px',
                    overflow: 'auto'
                  }}>
                    {JSON.stringify(currentRoute.meta, null, 2)}
                  </pre>
                </div>
              </div>
            )}

            <Row gutter={16}>
              <Col span={12}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>创建时间：</Text>
                  <div style={{ marginTop: 4 }}>
                    {new Date(currentRoute.created_at).toLocaleString()}
                  </div>
                </div>
              </Col>
              <Col span={12}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>更新时间：</Text>
                  <div style={{ marginTop: 4 }}>
                    {new Date(currentRoute.updated_at).toLocaleString()}
                  </div>
                </div>
              </Col>
            </Row>
          </div>
        )}
      </Modal>

      {/* 权限分配模态框 */}
      <Modal
        title={
          <Space>
            <SettingOutlined />
            为路由 "{currentRoute?.display_name}" 分配权限
          </Space>
        }
        open={isPermissionModalVisible}
        onCancel={() => {
          setIsPermissionModalVisible(false);
          setCurrentRoute(null);
          setSelectedPermissions([]);
        }}
        width="90%"
        style={{ maxWidth: '800px' }}
        footer={
          <div style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setIsPermissionModalVisible(false);
                setCurrentRoute(null);
                setSelectedPermissions([]);
              }}>
                取消
              </Button>
              <Button type="primary" onClick={handleSavePermissions}>
                保存权限
              </Button>
            </Space>
          </div>
        }
        destroyOnClose
      >
        <div style={{ marginBottom: 16 }}>
          <Text type="secondary">
            已选择 {selectedPermissions.length} 个权限
          </Text>
        </div>

        <div style={{
          border: '1px solid #d9d9d9',
          borderRadius: 6,
          padding: 16,
          maxHeight: 400,
          overflow: 'auto',
        }}>
          <Space direction="vertical" style={{ width: '100%' }}>
            {permissions.map(permission => (
              <div
                key={permission.id}
                style={{
                  padding: '8px 12px',
                  border: '1px solid #f0f0f0',
                  borderRadius: 4,
                  cursor: 'pointer',
                  backgroundColor: selectedPermissions.includes(permission.id)
                    ? 'rgba(24, 144, 255, 0.1)'
                    : 'transparent',
                }}
                onClick={() => {
                  if (selectedPermissions.includes(permission.id)) {
                    setSelectedPermissions(prev => prev.filter(id => id !== permission.id));
                  } else {
                    setSelectedPermissions(prev => [...prev, permission.id]);
                  }
                }}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <div style={{ fontWeight: 'bold' }}>{permission.display_name}</div>
                    <div style={{ fontSize: '12px', color: currentTheme.colorTextSecondary }}>
                      {permission.name}
                    </div>
                    {permission.description && (
                      <div style={{ fontSize: '12px', color: currentTheme.colorTextTertiary }}>
                        {permission.description}
                      </div>
                    )}
                  </div>
                  <div>
                    <Switch
                      checked={selectedPermissions.includes(permission.id)}
                      size="small"
                    />
                  </div>
                </div>
              </div>
            ))}
          </Space>
        </div>
      </Modal>

      {/* 拖拽排序模态框 */}
      <Modal
        title={
          <Space>
            <MenuOutlined />
            路由拖拽排序
          </Space>
        }
        open={isSortModalVisible}
        onCancel={() => setIsSortModalVisible(false)}
        width="90%"
        style={{ maxWidth: '800px' }}
        footer={null}
        destroyOnClose
      >
        <DragSortTree
          data={convertRoutesToSortData(routes)}
          onSave={handleBatchSort}
          onRefresh={() => {
            routesLoadedRef.current = false;
            fetchRoutes();
          }}
          loading={loading}
          title="路由层级排序"
        />
      </Modal>


    </div>
  );
};

export default RouteManagement;
